#include "dialog.h"
#include <QtGui>
#include <QSystemTrayIcon>
#include <QMenu>
#include <QTimer>
#include <QApplication>
#include "ui_dialog.h"
#include "wnditem.h"


Dialog::Dialog(QWidget *parent)
	: QDialog(parent),
	ui(new Ui::Dialog)
{
	ui->setupUi(this);
	settings = new QSettings("BemoSoft", qApp->applicationName(), this);

	// add buttons
	ui->buttonBox->clear();
	QPushButton * pbHide = ui->buttonBox->addButton(tr("&Hide"), QDialogButtonBox::ActionRole);
	connect(pbHide, SIGNAL(clicked()), this, SLOT(hide()));

	QPushButton * pbQuit = ui->buttonBox->addButton(tr("&Quit"), QDialogButtonBox::ActionRole);
	connect(pbQuit, SIGNAL(clicked()), qApp, SLOT(quit()));

	// create Quit action
	quitAction = new QAction(tr("&Quit"), this);
	quitAction->setShortcut(tr("Ctrl+W"));

	connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit()));

	// load the available styles for the filter
	loadStyles();

	// tray menu
	trayMenu = new QMenu(this);
	trayMenu->addAction(quitAction);
	pSeparator = trayMenu->insertSeparator(quitAction);

	// tray icon
	trayIcon = new QSystemTrayIcon(this);
	trayIcon->setContextMenu(trayMenu);

	trayIcon->setIcon(QIcon(":/plus"));


	m_pItems = new WndItems(settings, this);
	// ::RegisterHotKey(winId(), 100, MOD_CONTROL | MOD_ALT, 'Q');

	// connect
	connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
			this, SLOT(iconActivated(QSystemTrayIcon::ActivationReason)));	

	// create refresh timer
	timer = new QTimer(this);
	connect(timer, SIGNAL(timeout()), this, SLOT(onTimer()));
	timer->start(500);

	// show the tray icon
	trayIcon->show();
}

Dialog::~Dialog()
{
	// ::UnregisterHotKey(winId(), 12345);
	delete ui;
}

#include <qDebug>
bool Dialog::winEvent(MSG *message, long *result)
{
	qDebug()<<"Msg: "<<message->message<<" wParam: "<<message->wParam;
	if (message->message == WM_HOTKEY)
	{
		quitAction->trigger();
		*result = 0;
		return true;
	}	
	return QDialog::winEvent(message, result);
}

void Dialog::loadStyles()
{	
	QListWidgetItem * item = new QListWidgetItem("WS_VISIBLE", ui->listStyles);
	item->setCheckState(Qt::Checked);
	ui->listStyles->addItem(item);
}

void Dialog::iconActivated(QSystemTrayIcon::ActivationReason reason)
{
	switch (reason) {
	case QSystemTrayIcon::Trigger:
	case QSystemTrayIcon::DoubleClick:
		show();
		break;
	case QSystemTrayIcon::MiddleClick:
		break;
	default:
		trayIcon->contextMenu()->show();
	}
}

void Dialog::onTimer()
{
	m_pItems->update(WS_VISIBLE | WS_CLIPCHILDREN);

	m_pItems->populateMenu(*trayMenu, pSeparator);

	m_pItems->populateListWidget(*ui->listWidnows);
}
